/**
 * Copyright Green Tomato .ltd
 * www.gtomato.com
 * Author: Sam  Email:sam.lin@gtomato.com.cn
 * 2007
 * 上午10:15:30
 */
package com.linkwings.dbTemp;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class GenericsUtils {
	private static final Log log = LogFactory.getLog(GenericsUtils.class);

	/**
	 * 通过反射,获得定义Class时声明的父类的范型参数的类型.
	 * 如public BookManager extends GenricManager<Book>
	 *
	 * @param clazz The class to introspect
	 * @return the first generic declaration, or <code>Object.class</code> if cannot be determined
	 */
	public static Class getSuperClassGenricType(Class clazz) {
		return getSuperClassGenricType(clazz, 0);
	}

	/**
	 * 通过反射,获得定义Class时声明的父类的范型参数的类型.
	 * 如public BookManager extends GenricManager<Book>
	 *
	 * @param clazz clazz The class to introspect
	 * @param index the Index of the generic ddeclaration,start from 0.
	 */
	public static Class getSuperClassGenricType(Class clazz, int index) throws IndexOutOfBoundsException {

		Type genType = clazz.getGenericSuperclass();
		//clazz.get
		log.info(" the genType :"+genType+",clazz:"+clazz);
		log.info(" after the genType:" +genType.getClass().getGenericSuperclass());
		if (!(genType instanceof ParameterizedType)) {
			log.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType");
			return Object.class;
		}
		/*log.info((genType instanceof ParameterizedType) +" 111instance");
		log.info(((genType.getClass().getGenericSuperclass()) instanceof ParameterizedType) +" 111instance");
		*/
		ParameterizedType pt=(ParameterizedType) clazz.getGenericSuperclass();
		log.info(" [ParameterizedType] pt:"+pt.toString());

		Type[] params = ((ParameterizedType) genType).getActualTypeArguments();

		if (index >= params.length || index < 0) {
			log.error("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: " + params.length);
			return Object.class;
		}
		log.info(" params[index] :"+params[index]+",index:"+index);
		if (!(params[index] instanceof Class)) {
			log.error(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
			return Object.class;
		}
		return (Class) params[index];
	}

}
